import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../domain/entities/anime.dart';
import '../../core/utils/chinese_title_mapper.dart';
import 'dart:async';

/// 动漫轮播图组件
class AnimeBanner extends StatefulWidget {
  final List<Anime> animeList;
  final Function(Anime)? onTap;

  const AnimeBanner({
    super.key,
    required this.animeList,
    this.onTap,
  });

  @override
  State<AnimeBanner> createState() => _AnimeBannerState();
}

class _AnimeBannerState extends State<AnimeBanner> {
  final PageController _pageController = PageController();
  int _currentIndex = 0;
  Timer? _autoScrollTimer; // 使用Timer来管理自动轮播

  @override
  void initState() {
    super.initState();
    
    print('AnimeBanner 初始化，动漫数量: ${widget.animeList.length}');
    
    if (widget.animeList.isNotEmpty) {
      // 延迟启动自动轮播，确保组件完全构建
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _startAutoScroll();
      });
    }
  }

  @override
  void didUpdateWidget(AnimeBanner oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当数据更新时重新启动轮播
    if (oldWidget.animeList != widget.animeList) {
      print('AnimeBanner 数据更新，新数量: ${widget.animeList.length}');
      _currentIndex = 0; // 重置索引
      _autoScrollTimer?.cancel();
      WidgetsBinding.instance.addPostFrameCallback((_) {
      _startAutoScroll();
      });
    }
  }

  void _startAutoScroll() {
    // 取消之前的定时器
    _autoScrollTimer?.cancel();
    
    // 只有在有多张图片时才启动自动轮播
    if (widget.animeList.length > 1 && mounted) {
      print('启动自动轮播，间隔3秒，共${widget.animeList.length}张图片');
      _autoScrollTimer = Timer.periodic(const Duration(seconds: 3), (timer) {
        if (mounted && _pageController.hasClients) {
          final nextIndex = (_currentIndex + 1) % widget.animeList.length;
          print('自动轮播：${_currentIndex} -> $nextIndex');
          _pageController.animateToPage(
            nextIndex,
            duration: const Duration(milliseconds: 500),
            curve: Curves.easeInOut,
          );
        }
      });
    } else {
      print('不满足自动轮播条件：图片数量=${widget.animeList.length}, mounted=$mounted');
    }
  }

  @override
  void dispose() {
    _autoScrollTimer?.cancel();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.animeList.isEmpty) {
      return _buildPlaceholder();
    }

    return Container(
      height: 200,
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.15),
            blurRadius: 12,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Stack(
          children: [
            // 轮播图片
            PageView.builder(
              controller: _pageController,
              onPageChanged: _onPageChanged,
              itemCount: widget.animeList.length,
              itemBuilder: (context, index) {
                final anime = widget.animeList[index];
                return _buildBannerItem(anime);
              },
            ),
            
            // 指示器 - 只在有多张图片时显示
            if (widget.animeList.length > 1)
              Positioned(
                bottom: 16,
                left: 0,
                right: 0,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: List.generate(
                    widget.animeList.length,
                    (index) => Container(
                      margin: const EdgeInsets.symmetric(horizontal: 4),
                      width: _currentIndex == index ? 28 : 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: _currentIndex == index
                            ? Colors.white
                              : Colors.white.withValues(alpha: 0.6),
                        borderRadius: BorderRadius.circular(4),
                          boxShadow: [ // 添加阴影使指示器更明显
                            BoxShadow(
                              color: Colors.black.withValues(alpha: 0.3),
                              blurRadius: 2,
                              offset: const Offset(0, 1),
                            ),
                          ],
                      ),
                    ),
                  ),
                ),
              ),
            
            // 即将上线标签
            Positioned(
              top: 12,
              left: 12,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 8,
                  vertical: 4,
                ),
                decoration: BoxDecoration(
                  color: Colors.orange.withValues(alpha: 0.9),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: const Text(
                  '即将上线',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBannerItem(Anime anime) {
    return GestureDetector(
      onTap: () => widget.onTap?.call(anime),
      child: Stack(
        fit: StackFit.expand,
        children: [
          // 背景图片
          anime.imageUrl.isNotEmpty
              ? CachedNetworkImage(
                  imageUrl: anime.imageUrl,
                  fit: BoxFit.cover,
                  placeholder: (context, url) => Container(
                    color: Colors.grey[300],
                    child: const Center(
                      child: CircularProgressIndicator(),
                    ),
                  ),
                  errorWidget: (context, url, error) => Container(
                    color: _getGradientColor(anime.id),
                    child: const Center(
                      child: Icon(
                        Icons.image_not_supported,
                        color: Colors.white,
                        size: 48,
                      ),
                    ),
                  ),
                )
              : Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        _getGradientColor(anime.id),
                        _getGradientColor(anime.id).withValues(alpha: 0.7),
                      ],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                  ),
                ),
          
          // 渐变遮罩
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Colors.transparent,
                  Colors.black.withValues(alpha: 0.7),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
          ),
          
          // 动漫信息
          Positioned(
            bottom: 40,
            left: 16,
            right: 16,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  _getDisplayTitle(anime),
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    shadows: [
                      Shadow(
                        color: Colors.black,
                        offset: Offset(1, 1),
                        blurRadius: 3,
                      ),
                    ],
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  _getDisplayInfo(anime),
                  style: TextStyle(
                    color: Colors.white.withValues(alpha: 0.9),
                    fontSize: 14,
                    shadows: const [
                      Shadow(
                        color: Colors.black,
                        offset: Offset(1, 1),
                        blurRadius: 2,
                      ),
                    ],
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPlaceholder() {
    return Container(
      height: 180,
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: const Center(
        child: Text(
          '热门动漫轮播\n(即将上线)',
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 16),
        ),
      ),
    );
  }

  /// 获取显示标题，优先显示中文
  String _getDisplayTitle(Anime anime) {
    return ChineseTitleMapper.getBestChineseTitle(
      title: anime.title,
      titleJapanese: anime.titleJapanese,
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms,
    );
  }

  /// 获取显示信息
  String _getDisplayInfo(Anime anime) {
    final info = <String>[];
    
    if (anime.year != null) {
      info.add('${anime.year}年');
    }
    
    // 使用中文类型
    final chineseGenres = ChineseTitleMapper.getChineseGenres(anime.genres);
    if (chineseGenres.isNotEmpty) {
      info.add(chineseGenres.take(2).join(' · '));
    }
    
    if (anime.score > 0) {
      info.add('评分 ${anime.score.toStringAsFixed(1)}');
    }

    // 添加中文描述
    final description = ChineseTitleMapper.getChineseDescription(
      anime.title, 
      anime.genres, 
      anime.score,
    );
    if (description.isNotEmpty && description != '精彩动漫') {
      info.add(description);
    }
    
    return info.join(' | ');
  }

  /// 获取渐变色
  Color _getGradientColor(int id) {
    final colors = [
      Colors.blue,
      Colors.purple,
      Colors.orange,
      Colors.green,
      Colors.red,
    ];
    return colors[id % colors.length];
  }

  void _onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
} 